package com.orange.core.util;

import cn.hutool.core.collection.CollUtil;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>ClassName:ConvertUtils</p>
 * <p>Description: 实体类转VO工具类</p>
 * <p>Author: lwm</p>
 * <p>Date: 2025/5/24 17:08</p>
 */
public class ConvertUtils {

    /**
     * 单个对象转换
     * @param source
     * @param targetClass
     * @return
     * @param <S>
     * @param <T>
     */
    public static <S,T> T convertToVo(S source,Class<T> targetClass){
        if(source == null){
            return null;
        }
        try{
            T target = targetClass.getDeclaredConstructor().newInstance();
            BeanUtils.copyProperties(source,target);
            return target;
        }catch (Exception e){
            throw new RuntimeException("对象转换失败",e);
        }
    }

    /**
     * 列表对象转换
     * @param sourceList
     * @param targetClass
     * @return 转换后的列表，如果源列表为空则返回空列表
     * @param <S>
     * @param <T>
     */
    public static <S,T> List<T> convertListToVo(List<S> sourceList, Class<T> targetClass){
        if(CollUtil.isEmpty(sourceList)){
            return new ArrayList<>();
        }
        return sourceList.stream()
                .map(source -> convertToVo(source,targetClass))
                .collect(Collectors.toList());
    }
}
